class Line{
public:
    Vertex* A,* B,P;
    Uint32 color;
    Line():Line(nullptr,nullptr,0x000000){};
    Line(Vertex* _A,Vertex* _B):Line(_A,_B,0xffffff){};
    Line(Vertex* _A,Vertex* _B,Uint32 _color):A(_A),B(_B),color(_color){};
    void merge(Vertex* _A,Vertex* _B){
        A=_A;B=_B;
    };
    void merge(Vertex* _A,Vertex* _B,Uint32 _color){
        A=_A;B=_B;color=_color;
    };
    void draw(SDL_Renderer* renderer,SDL_Surface* ScSurface,Camara camara){
        SDL_SetRenderDrawColor(renderer,(color>>16)&0xff,(color>>8)&0xff,(color)&0xff,0xff);
        A->WorldToCamara(camara);
        B->WorldToCamara(camara);
        Uint32* ScPixels=static_cast<Uint32*>(ScSurface->pixels);
        int scw=ScSurface->w,sch=ScSurface->h;
        unsigned char state=0;//0b00:both|0b01:Acant|0b10Bcant|0b11none
        if(A->csz<=camara.n){
            state|=0b01;
        }
        if(B->csz<=camara.n){
            state|=0b10;
        }
        float lmd;
        switch(state){
        case 0b11:return;
        case 0b00:
            mylinedraw(A,B,color,ScPixels,scw,sch);
            // SDL_RenderDrawLine(renderer,A->scx,A->scy,B->scx,B->scy);
            break;
        case 0b01:
            P.csz=camara.n;
            lmd=(P.csz-B->csz)/(A->csz-B->csz);
            P.csx=B->csx+lmd*(A->csx-B->csx);
            P.csy=B->csy+lmd*(A->csy-B->csy);
            P.CamaraToScreen(camara);
            mylinedraw(&P,B,color,ScPixels,scw,sch);
            // SDL_RenderDrawLine(renderer,P.scx,P.scy,B->scx,B->scy);
            //// SDL_RenderDrawLine(renderer,P.scx,P.scy,A->scx,A->scy);
            break;
        case 0b10:
            P.csz=camara.n;
            lmd=(P.csz-A->csz)/(B->csz-A->csz);
            P.csx=A->csx+lmd*(B->csx-A->csx);
            P.csy=A->csy+lmd*(B->csy-A->csy);
            P.CamaraToScreen(camara);
            mylinedraw(A,&P,color,ScPixels,scw,sch);
            // SDL_RenderDrawLine(renderer,A->scx,A->scy,P.scx,P.scy);
            //// SDL_RenderDrawLine(renderer,B->scx,B->scy,P.scx,P.scy);
            break;
        default:return;
        }
    }
    void mylinedraw(Vertex* A,Vertex* B,Uint32 color,Uint32* ScPixels,int scw,int sch){
        float step=1/std::max(abs(A->scx-B->scx),abs(A->scy-B->scy));
        for(float i=0.0;i<=1.0;i+=step){
            int x=A->scx*(1.0-i)+B->scx*i;
            int y=A->scy*(1.0-i)+B->scy*i;
            int z=A->scz*(1.0-i)+B->scz*i;
            if(x<0||y<0||x>=SCREEN_W||y>=SCREEN_H||z<0){
                continue;
            }
            if(z>=Z_buffer[y*SCREEN_W+x]){
                ScPixels[y*scw+x]=color;
                Z_buffer[y*SCREEN_W+x]=z;
            }
        }
    }
};
